<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="500px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <template #scriptSlot>
        <FormItemRest>
          <RadioGroup
            v-model:value="dataRef.btnBatchOrScript"
            button-style="solid"
            style="margin-bottom: 10px"
          >
            <template v-for="item in scriptSlotList" :key="`${item.value}`">
              <RadioButton :value="item.value">
                {{ item.label }}
              </RadioButton>
            </template>
          </RadioGroup>
          <div class="flex gap-10px items-center" v-if="dataRef.btnBatchOrScript == '0'">
            置
            <Select
              :options="formGetFieldsData"
              v-model:value="dataRef['batchField']"
              placeholder="请选择"
              style="flex: 1"
              showSearch
              optionFilterProp="label"
            />
            为
            <Input v-model:value="dataRef['batchValue']" placeholder="请输入" style="flex: 1" />
          </div>
          <div class="flex gap-10px items-center" v-if="dataRef.btnBatchOrScript == '1'">
            <InputTextArea
              v-model:value="dataRef['btnScript']"
              placeholder="请输入"
              style="flex: 1"
            />
          </div>
          <div class="flex gap-10px items-center" v-if="dataRef.btnBatchOrScript == '2'">
            <TreeSelect
              style="flex: 1"
              :tree-data="treeData"
              :field-names="{ label: 'name', value: 'code', key: 'code' }"
              :show-search="true"
              treeNodeFilterProp="name"
              v-model:value="dataRef['flowTypeCode']"
            />
            <Select
              :options="isSelRowList"
              v-model:value="dataRef['isSelRow']"
              placeholder="请选择"
              style="flex: 1"
              showSearch
              optionFilterProp="label"
            />
          </div>
          <div class="flex gap-10px flex-col" v-if="dataRef.btnBatchOrScript == '3'">
            <div class="flex gap-10px items-center">
              <Select
                style="flex: 1"
                :options="moduleList"
                v-model:value="dataRef['moduleCode']"
                placeholder="请选择"
                showSearch
                optionFilterProp="name"
                :field-names="{ label: 'name', value: 'code' }"
              />
              <Select
                :options="modeList"
                v-model:value="dataRef['mode']"
                placeholder="请选择"
                style="flex: 1"
                showSearch
                optionFilterProp="label"
              />
              <Select
                :options="isSelRowList"
                v-model:value="dataRef['isSelRow']"
                placeholder="请选择"
                style="flex: 1"
                showSearch
                optionFilterProp="label"
              />
            </div>
            <div class="flex gap-10px items-center">
              限选<InputNumber style="flex: 1" v-model:value="dataRef['selRowMax']" />条 提交参数
              op=<Input
                v-model:value="dataRef['moduleAction']"
                placeholder="请输入"
                style="flex: 1"
              />
            </div>
          </div>
        </FormItemRest>
      </template>
      <template #role>
        <SelectRoleInput
          :roleCodes="dataRef.roleCodes"
          v-model:value="dataRef.roleDescs"
          @change="(val, node) => handleRoleNames(val, node)"
        />
      </template>
      <template #iconLinkAdd>
        <FormItemRest>
          <div class="flex gap-10px items-center">
            <Select
              v-model:value="dataRef['btnBclass']"
              placeholder="请选择"
              style="flex: 1"
              showSearch
              optionFilterProp="label"
              :filter-option="filterOption"
            >
              <SelectOption
                v-for="item in flowMacroGetFontAwesomeList"
                :value="item.value"
                :key="item.value"
              >
                <i :class="`fa ${item.label}`"></i> {{ item.label }}
              </SelectOption>
            </Select>
          </div>
        </FormItemRest>
      </template>
    </BasicForm>
    <ConfigurationModal
      @register="registerConfigurationModal"
      @success="handleSuccessConfigurationModal"
    />
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref, onMounted } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema, scriptSlotList, isSelRowList, modeList } from './buttonList.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { useModal } from '/@/components/Modal';
  import { getFlowGetDirTreeAll, getFlowMacroGetFontAwesome } from '/@/api/flowManage/flowManage';
  import { getDirTreeOpened } from '/@/api/process/process';
  import { Form, Select, Input, TreeSelect, Radio, InputNumber } from 'ant-design-vue';
  import { TreeItem } from '/@/components/Tree';
  import { SelectRoleInput } from '/@/components/CustomComp';
  import ConfigurationModal from '../../configuration/index';
  import { getModulesAll } from '/@/api/system/system';
  import { getVisualBtnAdd, getVisualBtnModify } from '/@/api/module/module';
  import { isArray } from '/@/utils/is';

  export default defineComponent({
    name: 'ButtonListDrawer',
    components: {
      BasicDrawer,
      BasicForm,
      FormItemRest: Form.ItemRest,
      Select,
      SelectOption: Select.Option,
      Input,
      SelectRoleInput,
      TreeSelect,
      ConfigurationModal,
      RadioGroup: Radio.Group,
      RadioButton: Radio.Button,
      InputTextArea: Input.TextArea,
      InputNumber,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      let dataRef = ref<any>({});
      const formCode = ref('');
      const moduleCode = ref('');
      const moduleList = ref<Recordable[]>([]);

      const formGetFieldsData = ref<Recordable[]>([]);
      // const formFieldList = ref<Recordable[]>([]);
      const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
        labelWidth: 110,
        schemas: formSchema,
        showActionButtonGroup: false,
      });

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        formCode.value = data?.formCode ?? '';
        moduleCode.value = data?.moduleCode ?? '';
        formGetFieldsData.value = data?.formGetFieldsData;
        dataRef.value = {};
        // getFormGetFieldsData();
        if (unref(isUpdate)) {
          const _data = data?.record;
          dataRef.value = {
            btnOrder: _data?.btnOrder,
            btnName: _data?.name,
            btnNewName: _data?.name,
            // op: 'addBtnBatch',
            btnBatchOrScript:
              _data?.type == 'batchBtn'
                ? '0'
                : _data?.type == 'script'
                ? '1'
                : _data?.type == 'flowBtn'
                ? '2'
                : _data?.type == 'moduleBtn'
                ? '3'
                : '',
            batchField: _data?.batchField ?? '',
            batchValue: _data?.batchValue ?? '',
            btnScript: _data?.script ?? '',
            flowTypeCode: _data?.flowTypeCode ?? '',
            moduleCode: _data?.moduleCode ?? '',
            mode: _data?.mode ?? '',
            isSelRow: _data?.isSelRow ?? false,
            selRowMax: _data?.selRowMax ?? '',
            moduleAction: _data?.moduleAction ?? '',
            roleDescs: _data?.roleDescs ?? '',
            roleCodes: _data?.roleCodes ?? '',
            btnBclass: _data?.icon ?? '',
          };
          updateSchema([
            {
              field: 'btnName',
              ifShow: false,
            },
          ]);
          updateSchema([
            {
              field: 'btnNewName',
              ifShow: true,
            },
          ]);
        } else {
          dataRef.value = {
            btnOrder: data?.dataSourceLength ? data?.dataSourceLength + 1 : 1,
            btnName: '',
            op: 'addBtnBatch',
            btnBatchOrScript: '0',
            batchField: '',
            batchValue: '',
            btnScript: '',
            flowTypeCode: '',
            moduleCode: '',
            mode: 1,
            isSelRow: false,
            selRowMax: '',
            moduleAction: '',
            roleDescs: '',
            roleCodes: '',
            btnBclass: '',
            formCode: '',
            code: '',
          };
          if (formGetFieldsData.value && formGetFieldsData.value.length) {
            dataRef.value.batchField = formGetFieldsData.value[0].value;
          }
          updateSchema([
            {
              field: 'btnName',
              ifShow: true,
            },
          ]);
          updateSchema([
            {
              field: 'btnNewName',
              ifShow: false,
            },
          ]);
        }
        setFieldsValue({
          ...unref(dataRef),
        });
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

      //获取所有模块
      const getModulesAllData = async () => {
        moduleList.value = (await getModulesAll()) || [];
      };

      const flowMacroGetFontAwesomeList = ref<Recordable[]>([]);
      //获取所有图标
      const getFlowMacroGetFontAwesomeData = async () => {
        flowMacroGetFontAwesomeList.value = [];
        const data = (await getFlowMacroGetFontAwesome()) || [];
        if (isArray(data)) {
          data.forEach((item) => {
            flowMacroGetFontAwesomeList.value.push({
              value: item,
              label: item,
            });
          });
        }
      };
      const treeData = ref<TreeItem[]>([]);
      const fetch = async () => {
        const data = (await getDirTreeOpened()) || [];
        treeData.value = setChildren(data);
        getModulesAllData();
        getFlowMacroGetFontAwesomeData();
      };

      function setChildren(node) {
        node.forEach((item) => {
          item.key = item.code;
          item.value = item.code;
          item.title = item.name;
          item.disabled = item.layer == 3 ? false : true;
          if (item.children && Array.isArray(item.children) && item.children.length > 0) {
            item.isLeaf = false;
            setChildren(item.children);
          } else {
            item.isLeaf = true;
          }
        });
        return node;
      }
      onMounted(fetch);
      //获取数据
      // const getFormGetFieldsData = () => {
      //   formFieldList.value = [];
      //   try {
      //     if (!formCode.value) return;
      //     getFormGetFields({ formCode: formCode.value }).then((res) => {
      //       formFieldList.value = res || [];
      //       formFieldList.value.forEach((item: Recordable) => {
      //         delete item.options;
      //         item.value = item.name;
      //         item.label = item.title;
      //       });
      //     });
      //     getFieldsWithNest({ formCode: formCode.value });
      //   } catch (err) {
      //     console.log('getFormGetFields', err);
      //   }
      // };

      const handleRoleNames = (val, node) => {
        const { dataRef: newDataRef } = node;
        dataRef.value.roleDescs = val;
        dataRef.value.roleCodes = newDataRef['codes'];
      };

      //配置条件
      const [registerConfigurationModal, { openModal: openConfiguration }] = useModal();
      //组合条件配置
      const handleConfiguration = () => {
        openConfiguration(true, {
          list: dataRef.value.linkFieldCond || [],
          formGetFieldsData: formGetFieldsData.value,
        });
      };

      const handleSuccessConfigurationModal = ({ value }) => {
        dataRef.value.linkFieldCond = value;
      };

      async function handleSubmit() {
        try {
          const values = await validate();
          let formData = Object.assign({}, unref(dataRef), values);
          formData.code = moduleCode.value;
          formData.formCode = formCode.value;
          if (formData.linkEvent == 'flow') {
            formData.linkHref = formData.params ? JSON.stringify(formData.params) : '';
            formData.params = formData.params ? JSON.stringify(formData.params) : '';
          }

          setDrawerProps({ confirmLoading: true });
          console.log(formData);
          if (unref(isUpdate)) {
            // formData.btnNewName = formData.btnName;
            await getVisualBtnModify(formData);
          } else {
            formData.op =
              formData.btnBatchOrScript == '0'
                ? 'addBtnBatch'
                : formData.btnBatchOrScript == '1'
                ? 'addBtnScript'
                : formData.btnBatchOrScript == '2'
                ? 'addBtnFlow'
                : formData.btnBatchOrScript == '3'
                ? 'addBtnModule'
                : '';
            await getVisualBtnAdd(formData);
          }
          closeDrawer();
          emit('success');
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }
      const filterOption = (input: string, option: any) => {
        return option.value.toLowerCase().indexOf(input.toLowerCase()) >= 0;
      };
      return {
        registerDrawer,
        registerForm,
        getTitle,
        handleSubmit,
        dataRef,
        handleRoleNames,
        handleConfiguration,
        treeData,
        registerConfigurationModal,
        handleSuccessConfigurationModal,
        moduleList,
        flowMacroGetFontAwesomeList,
        filterOption,
        scriptSlotList,
        isSelRowList,
        modeList,
        formGetFieldsData,
      };
    },
  });
</script>
